package vigo_tool

import (
	"github.com/garyburd/redigo/redis"
	"permission/config"
)

type RedisCacheFactory struct {
	RedPool *redis.Pool
	Prefix  string
	Expire int64
	conn redis.Conn
}

func NewRedisFactory() *RedisCacheFactory {
	var red RedisCacheFactory
	red.RedPool = RedisPool
	red.Prefix = config.REDIS_PREFIX
	red.Expire = 300 // 过期时间 5 sec
	//red.conn = red.RedPool.Get()
	return &red
}

// todo
func (red *RedisCacheFactory) Close() error {
	return nil
	//return red.conn.Close()
}

func (red *RedisCacheFactory) Set(key string, value interface{}) error {
	key = red.Prefix + key
	redcon := red.RedPool.Get()
	_, err := redcon.Do("Set", key, value)
	if err != nil {
		redcon.Close()
		return err
	}
	redcon.Do("EXPIRE", key, red.Expire)
	redcon.Close()
	return nil
}

func (red *RedisCacheFactory) Get(key string) (interface{}, error) {
	key = red.Prefix + key
	redcon := red.RedPool.Get()
	val, err := redcon.Do("Get", key)
	redcon.Close()
	if err != nil {
		return nil, err
	}
	return val, nil
}

func (red *RedisCacheFactory) SetNx(key string, value interface{}) (interface{}, error) {
	key = red.Prefix + key
	redcon := red.RedPool.Get()
	defer redcon.Close()
	val, err := redcon.Do("SETNX", key, value)
	if err != nil {
		return nil, err
	}
	return val, nil
}

func (red *RedisCacheFactory) Del(key string) (interface{}, error) {
	key = red.Prefix + key
	redcon := red.RedPool.Get()
	val, err := redcon.Do("DEL", key)
	redcon.Close()
	if err != nil {
		return nil, err
	}
	return val, nil
}

func (red *RedisCacheFactory) GetSet(key string, value interface{}) (interface{}, error) {
	key = red.Prefix + key
	redcon := red.RedPool.Get()
	defer redcon.Close()
	val, err := redcon.Do("GETSET", key, value)
	if err != nil {
		return nil, err
	}
	redcon.Do("EXPIRE", key, red.Expire)
	return val, nil
}

func (red *RedisCacheFactory) SetExpire(expireTime int64) {
	red.Expire = expireTime
}

func (red *RedisCacheFactory) GetExpire() int64 {
	return red.Expire
}
